import 'package:flutter/material.dart';
import 'package:sunmi_status_light_manager/sunmi_status_light_manager.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Sunmi Status Light Manager Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        useMaterial3: true,
      ),
      home: const StatusLightDemo(),
    );
  }
}

class StatusLightDemo extends StatefulWidget {
  const StatusLightDemo({super.key});

  @override
  State<StatusLightDemo> createState() => _StatusLightDemoState();
}

class _StatusLightDemoState extends State<StatusLightDemo> {
  final SunmiStatusLightManager _statusLightManager = SunmiStatusLightManager();

  StatusLightColor _selectedColor = StatusLightColor.red;
  bool _isInitialized = false;
  int _onMs = 500;
  int _offMs = 500;

  @override
  void initState() {
    super.initState();
    _initializePlugin();
  }

  Future<void> _initializePlugin() async {
    try {
      final initialized = await _statusLightManager.initialize();

      setState(() {
        _isInitialized = initialized;
      });

      if (initialized) {
        _showSnackBar('状态灯管理器初始化成功');
      } else {
        _showSnackBar('状态灯管理器初始化失败');
      }
    } catch (e) {
      _showSnackBar('初始化失败: $e');
    }
  }

  Future<void> _setColor() async {
    if (!_isInitialized) {
      _showSnackBar('请先初始化状态灯管理器');
      return;
    }

    try {
      final success = await _statusLightManager.setColor(_selectedColor);
      if (success) {
        _showSnackBar('${_getColorName(_selectedColor)}设置成功');
      } else {
        _showSnackBar('设置颜色失败');
      }
    } catch (e) {
      _showSnackBar('设置颜色时出错: $e');
    }
  }

  Future<void> _turnOff() async {
    if (!_isInitialized) {
      _showSnackBar('请先初始化状态灯管理器');
      return;
    }

    try {
      final success = await _statusLightManager.turnOff();
      if (success) {
        _showSnackBar('状态灯已关闭');
      } else {
        _showSnackBar('关闭状态灯失败');
      }
    } catch (e) {
      _showSnackBar('关闭状态灯时出错: $e');
    }
  }

  Future<void> _setFlashing() async {
    if (!_isInitialized) {
      _showSnackBar('请先初始化状态灯管理器');
      return;
    }

    try {
      final success =
          await _statusLightManager.setFlashing(_selectedColor, _onMs, _offMs);
      if (success) {
        _showSnackBar('${_getColorName(_selectedColor)}闪烁设置成功');
      } else {
        _showSnackBar('设置闪烁失败');
      }
    } catch (e) {
      _showSnackBar('设置闪烁时出错: $e');
    }
  }

  Future<void> _setMultiFlashing() async {
    if (!_isInitialized) {
      _showSnackBar('请先初始化状态灯管理器');
      return;
    }

    try {
      final colors = [
        StatusLightColor.red,
        StatusLightColor.green,
        StatusLightColor.blue
      ];
      final onMs = [_onMs, _onMs, _onMs];
      final offMs = [_offMs, _offMs, _offMs];

      final success =
          await _statusLightManager.setMultiFlashing(colors, onMs, offMs);
      if (success) {
        _showSnackBar('多色闪烁设置成功');
      } else {
        _showSnackBar('设置多色闪烁失败');
      }
    } catch (e) {
      _showSnackBar('设置多色闪烁时出错: $e');
    }
  }

  Future<void> _destroy() async {
    try {
      final success = await _statusLightManager.destroy();
      if (success) {
        setState(() {
          _isInitialized = false;
        });
        _showSnackBar('状态灯管理器已销毁');
      } else {
        _showSnackBar('销毁状态灯管理器失败');
      }
    } catch (e) {
      _showSnackBar('销毁时出错: $e');
    }
  }

  void _showSnackBar(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(content: Text(message)),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('商米状态灯管理器'),
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 设备信息卡片
            Card(
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      '设备信息',
                      style: Theme.of(context).textTheme.headlineSmall,
                    ),
                    const SizedBox(height: 8),
                    Text('初始化状态: ${_isInitialized ? "已初始化" : "未初始化"}'),
                  ],
                ),
              ),
            ),

            const SizedBox(height: 16),

            // 颜色选择
            Card(
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      '选择颜色',
                      style: Theme.of(context).textTheme.headlineSmall,
                    ),
                    const SizedBox(height: 8),
                    Wrap(
                      spacing: 8,
                      children: StatusLightColor.values.map((color) {
                        return ChoiceChip(
                          label: Text(_getColorName(color)),
                          selected: _selectedColor == color,
                          onSelected: (selected) {
                            if (selected) {
                              setState(() {
                                _selectedColor = color;
                              });
                            }
                          },
                        );
                      }).toList(),
                    ),
                  ],
                ),
              ),
            ),

            const SizedBox(height: 16),

            // 闪烁参数设置
            Card(
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      '闪烁参数设置',
                      style: Theme.of(context).textTheme.headlineSmall,
                    ),
                    const SizedBox(height: 16),

                    // 亮的时间
                    Text('亮的时间 (毫秒):'),
                    Slider(
                      value: _onMs.toDouble(),
                      min: 100,
                      max: 2000,
                      divisions: 19,
                      label: '${_onMs}ms',
                      onChanged: (value) {
                        setState(() {
                          _onMs = value.round();
                        });
                      },
                    ),

                    const SizedBox(height: 16),

                    // 灭的时间
                    Text('灭的时间 (毫秒):'),
                    Slider(
                      value: _offMs.toDouble(),
                      min: 100,
                      max: 2000,
                      divisions: 19,
                      label: '${_offMs}ms',
                      onChanged: (value) {
                        setState(() {
                          _offMs = value.round();
                        });
                      },
                    ),
                  ],
                ),
              ),
            ),

            const SizedBox(height: 16),

            // 控制按钮
            Card(
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      '状态灯控制',
                      style: Theme.of(context).textTheme.headlineSmall,
                    ),
                    const SizedBox(height: 16),

                    // 单色控制
                    Row(
                      children: [
                        Expanded(
                          child: ElevatedButton.icon(
                            onPressed: _isInitialized ? _setColor : null,
                            icon: const Icon(Icons.lightbulb),
                            label: Text('设置${_getColorName(_selectedColor)}'),
                          ),
                        ),
                        const SizedBox(width: 8),
                        Expanded(
                          child: ElevatedButton.icon(
                            onPressed: _isInitialized ? _turnOff : null,
                            icon: const Icon(Icons.lightbulb_outline),
                            label: const Text('关闭'),
                            style: ElevatedButton.styleFrom(
                              backgroundColor: Colors.red,
                              foregroundColor: Colors.white,
                            ),
                          ),
                        ),
                      ],
                    ),

                    const SizedBox(height: 8),

                    // 闪烁控制
                    Row(
                      children: [
                        Expanded(
                          child: ElevatedButton.icon(
                            onPressed: _isInitialized ? _setFlashing : null,
                            icon: const Icon(Icons.flash_on),
                            label: Text('${_getColorName(_selectedColor)}闪烁'),
                          ),
                        ),
                        const SizedBox(width: 8),
                        Expanded(
                          child: ElevatedButton.icon(
                            onPressed:
                                _isInitialized ? _setMultiFlashing : null,
                            icon: const Icon(Icons.color_lens),
                            label: const Text('多色闪烁'),
                          ),
                        ),
                      ],
                    ),

                    const SizedBox(height: 8),

                    // 管理按钮
                    Row(
                      children: [
                        Expanded(
                          child: ElevatedButton.icon(
                            onPressed:
                                !_isInitialized ? _initializePlugin : null,
                            icon: const Icon(Icons.play_arrow),
                            label: const Text('初始化'),
                            style: ElevatedButton.styleFrom(
                              backgroundColor: Colors.green,
                              foregroundColor: Colors.white,
                            ),
                          ),
                        ),
                        const SizedBox(width: 8),
                        Expanded(
                          child: ElevatedButton.icon(
                            onPressed: _isInitialized ? _destroy : null,
                            icon: const Icon(Icons.stop),
                            label: const Text('销毁'),
                            style: ElevatedButton.styleFrom(
                              backgroundColor: Colors.orange,
                              foregroundColor: Colors.white,
                            ),
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ),

            const SizedBox(height: 16),

            // 快速测试按钮
            Card(
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      '快速测试',
                      style: Theme.of(context).textTheme.headlineSmall,
                    ),
                    const SizedBox(height: 8),
                    Wrap(
                      spacing: 8,
                      runSpacing: 8,
                      children: [
                        ElevatedButton(
                          onPressed: _isInitialized
                              ? () => _quickTest(StatusLightColor.red)
                              : null,
                          child: const Text('红色'),
                        ),
                        ElevatedButton(
                          onPressed: _isInitialized
                              ? () => _quickTest(StatusLightColor.green)
                              : null,
                          child: const Text('绿色'),
                        ),
                        ElevatedButton(
                          onPressed: _isInitialized
                              ? () => _quickTest(StatusLightColor.blue)
                              : null,
                          child: const Text('蓝色'),
                        ),
                        ElevatedButton(
                          onPressed: _isInitialized
                              ? () => _quickTest(StatusLightColor.yellow)
                              : null,
                          child: const Text('黄色'),
                        ),
                        ElevatedButton(
                          onPressed: _isInitialized
                              ? () => _quickTest(StatusLightColor.magenta)
                              : null,
                          child: const Text('品红'),
                        ),
                        ElevatedButton(
                          onPressed: _isInitialized
                              ? () => _quickTest(StatusLightColor.cyan)
                              : null,
                          child: const Text('青色'),
                        ),
                        ElevatedButton(
                          onPressed: _isInitialized
                              ? () => _quickTest(StatusLightColor.white)
                              : null,
                          child: const Text('白色'),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Future<void> _quickTest(StatusLightColor color) async {
    try {
      final success = await _statusLightManager.setColor(color);
      if (success) {
        _showSnackBar('${_getColorName(color)}测试成功');
      } else {
        _showSnackBar('${_getColorName(color)}测试失败');
      }
    } catch (e) {
      _showSnackBar('测试时出错: $e');
    }
  }

  String _getColorName(StatusLightColor color) {
    switch (color) {
      case StatusLightColor.red:
        return '红色';
      case StatusLightColor.green:
        return '绿色';
      case StatusLightColor.blue:
        return '蓝色';
      case StatusLightColor.yellow:
        return '黄色';
      case StatusLightColor.magenta:
        return '品红';
      case StatusLightColor.cyan:
        return '青色';
      case StatusLightColor.white:
        return '白色';
    }
  }
}
